var googleMap;
var ownerships;
var flightsAround=[];
var airportsAround=[];
var ownershipsAround=[];
var itemsToBuy;

var radarUpdateTime = 5000;
var flightUpdateTime = 100;

function insertMarker(image,lat,lon){
    var myLatLng = new google.maps.LatLng(lat,lon);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: googleMap,
        icon: image
    });
    
    return marker;
}

function changeMarkerPosition(marker,lat,lon){
	var newLatLng = new google.maps.LatLng(lat,lon);
	
	marker.setPosition(newLatLng);
}
  
function initialize() {
    var latlng = new google.maps.LatLng(40,32);
    var myOptions = {
      zoom: 8,
      center: latlng,
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    
    googleMap = map;
    
    google.maps.event.addListener(googleMap, 'zoom_changed', function() {
        if (map.getZoom() < 7) map.setZoom(7);
      });
    
    $( "#loginScreen" ).dialog({
		   resizable: false
	   });

  }

function login(username){
	$.ajax({
		   type: "POST",
		   url: "/FlightGame/app/game/login",
		   data:"username="+username+"&password=12345",
		   dataType:"json",
		   success: function(json){
			   if(json.success ==  'true'){
				   setUIValue('userCredits',json.user.credits);
				   ownerships = json.user.ownerships;
				   itemsToBuy = json.itemstobuy;
				   
				   $( "#loginScreen" ).dialog('close');
				   $( "#userControlPanel" ).dialog({
					   resizable: false,
					   position	: 'left'
				   });
				   
			   }
			   else{
				   $( "#loginStatus" ).text(json.mess);
			   }
			   
		   }
		 });
}

  
function buyItemOnMap(username,selectedItemId){
	google.maps.event.clearListeners(googleMap,'click');
	var buyItemClickListener = google.maps.event.addListener(googleMap,'click',function(event) {
		var lat = event.latLng.lat();
		var lon = event.latLng.lng();
		google.maps.event.removeListener(buyItemClickListener);
		
		for(var i=0;i < itemsToBuy.length ; i++){
			if(itemsToBuy[i].itemname == selectedItemId){
				var data = "username="+username+"&itemname="+selectedItemId+"&lat="+lat+"&lon="+lon;
				if(itemsToBuy[i].type == 'aircraft') data += "&airportcode=ESB";
				
				$.ajax({
					   type: "POST",
					   url: "/FlightGame/app/game/buyitem",
					   data: data,
					   dataType: "json",
					   success: function(json){
						   //viewAircrafts(json,aircraftId);
						   setUIValue('userCredits',json.params.credits);
						   getOwnershipsAround();
					   }
				});
			}	
		} 
	});
}